package sample.springframework_practice.dao.impl;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import sample.springframework_practice.dao.MessageSequenceDao;
import sample.springframework_practice.entity.MessageSequence;

@Repository
public class MessageSequenceDaoImpl extends JdbcDaoSupport implements MessageSequenceDao {

    @Autowired
    public MessageSequenceDaoImpl(DataSource dataSource) {
	setDataSource(dataSource);
    }

    @Override
    public MessageSequence selectCurrentNumberForUpdate() {
	final String sql = "SELECT current_number FROM message_sequence FOR UPDATE";
	return getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<MessageSequence>(MessageSequence.class));
    }

    @Override
    public int updateCurrentNumber(MessageSequence messageSequence) {
	Assert.notNull(messageSequence);
	final String sql = "UPDATE message_sequence SET current_number = ?";
	return getJdbcTemplate().update(sql, messageSequence.getCurrentNumber());
    }
}
